package sunyu.tools.common;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * xml相关工具类
 * <p>
 * 主要用于xml与java bean之间的转换
 *
 * @author 孙宇
 */
@Component
public class XmlTools {

    private static ObjectMapper xmlMapper = new XmlMapper();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public String toXml(Object obj) {
        try {
            return xmlMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public Map toMap(String xml) {
        try {
            return xmlMapper.readValue(xml, Map.class);
        } catch (IOException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    public <T> T toBean(String xml,
                        Class<T> clazz) {
        try {
            return xmlMapper.readValue(xml, clazz);
        } catch (IOException e) {
            logger.error(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

}
